package com.llmops.core.node;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.llmops.core.Context;
import com.llmops.core.Node;
import com.llmops.core.NodeProperty;
import com.llmops.core.WorkflowGraph;
import lombok.Data;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class ForNode extends Node {
    //TODO 线程池
    private WorkflowGraph workflowGraph;

    private UserInputNodeProperty property = new UserInputNodeProperty();
    @Data
    public static class UserInputNodeProperty extends NodeProperty {
        private Integer maxTimes;
        private String listName;
    }
    public ForNode(String id,String title, Map<String, Object> config,WorkflowGraph workflowGraph) {
        super(id,title,config);
        this.property.setMaxTimes((Integer) config.get("maxTimes"));
        this.property.setListName((String) config.get("listName"));
        this.workflowGraph = workflowGraph;
    }

    @Override
    public void execute(Context context) {
        Context contextLocal = new Context();
        List<String> listValue = context.getVariable(this.property.getListName());
        List<Object> result = new ArrayList<>();
        for (int i = 0; i < listValue.size(); i++) {
            contextLocal.setVariable("input",listValue.get(i));
            workflowGraph.execute(contextLocal);
            result.add(contextLocal.getVariable("result"));
            if(i+1== property.getMaxTimes()){
                logger.warn("超过迭代上限,退出迭代");
                break;
            }
        }
        context.setVariable(getId() + "_output", JSON.toJSONString(result));
        logger.info(getId() + "_output={}", JSON.toJSONString(result));
    }

    @Override
    public String getType() {
        return "forNode";
    }
}